package com.zhangzhan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangzhan.domain.commcon.ResponseResult;
import com.zhangzhan.domain.dto.ChangeStatusDto;
import com.zhangzhan.domain.dto.RoleLikeDto;
import com.zhangzhan.domain.dto.SaveRoleMenuDto;
import com.zhangzhan.domain.dto.UpdateRoleMenuDto;
import com.zhangzhan.domain.entity.Role;
import com.zhangzhan.domain.entity.RoleMenu;
import com.zhangzhan.domain.vo.PageVO;
import com.zhangzhan.domain.vo.SelectRoleByIdVO;
import com.zhangzhan.domain.vo.SelectUserVO;
import com.zhangzhan.mapper.RoleMapper;
import com.zhangzhan.service.RoleMenuService;
import com.zhangzhan.service.RoleService;
import com.zhangzhan.utils.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 角色信息表(Role)表服务实现类
 *
 * @author makejava
 * @since 2022-12-05 15:06:49
 */
@Service("roleService")
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    RoleMenuService roleMenuService;

    /**
     * @param id
     * @return java.util.List<java.lang.String>
     * @description 用户角色
     * @author 31115
     * @date 2022/12/5 17:05
     */
    @Override
    public List<String> selectRoleKeyByUserId(Long id) {
        //如果用户id等于1 直接返回admin
        if (id == 1) {
            List<String> list = new ArrayList<>();
            list.add("admin");
            return list;
        }

        //如果是其他用户 则返回已有的用户角色
        return getBaseMapper().selectRoleKeyByUserId(id);
    }

    /**
     * @param pageNum
     * @param pageSize
     * @param roleLikeDto
     * @return com.zhangzhan.domain.commcon.ResponseResult<com.zhangzhan.domain.vo.PageVO>
     * @description 分页查询
     * @author 31115
     * @date 2022/12/7 14:55
     */
    @Override
    public ResponseResult<PageVO> pageList(Integer pageNum, Integer pageSize, RoleLikeDto roleLikeDto) {

        if ("".equals(roleLikeDto.getStatus())) {
            roleLikeDto.setStatus("0");
        }
        Page<Role> rolePage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(roleLikeDto.getRoleName() != null, Role::getRoleName, roleLikeDto.getRoleName());
        wrapper.eq(roleLikeDto.getStatus() != null, Role::getStatus
                , roleLikeDto.getStatus());
        wrapper.orderByAsc(Role::getRoleSort);
        page(rolePage, wrapper);
        List<Role> records = rolePage.getRecords();

        return ResponseResult.okResult(new PageVO(records, rolePage.getTotal()));
    }

    /**
     * @param change
     * @return com.zhangzhan.domain.commcon.ResponseResult
     * @description 修改状态
     * @author 31115
     * @date 2022/12/7 15:12
     */
    @Override
    public ResponseResult changeStatus(ChangeStatusDto change) {
        LambdaUpdateWrapper<Role> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Role::getId, change.getRoleId())
                .set(Role::getStatus, change.getStatus());

        update(wrapper);

        return ResponseResult.okResult();
    }

    /**
     * @param saveRoleMenuDto
     * @return com.zhangzhan.domain.commcon.ResponseResult
     * @description 新增角色
     * @author 31115
     * @date 2022/12/7 21:16
     */
    @Override
    public ResponseResult saveRoleMenu(SaveRoleMenuDto saveRoleMenuDto) {
        Role role = BeanCopyUtils.beanCopyUtils(saveRoleMenuDto, Role.class);
        save(role);

        List<RoleMenu> roleMenus = saveRoleMenuDto.getMenuIds()
                .stream()
                .map(new Function<Long, RoleMenu>() {
                    @Override
                    public RoleMenu apply(Long menuId) {
                        RoleMenu roleMenu = new RoleMenu();
                        roleMenu.setMenuId(menuId);
                        roleMenu.setRoleId(role.getId());
                        return roleMenu;
                    }
                }).collect(Collectors.toList());

        roleMenuService.saveBatch(roleMenus);

        return ResponseResult.okResult();
    }

    /**
     * @param id
     * @return com.zhangzhan.domain.commcon.ResponseResult
     * @description 修改前回显
     * @author 31115
     * @date 2022/12/7 21:42
     */
    @Override
    public ResponseResult<SelectRoleByIdVO> selectRoleById(Long id) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getId, id);
        Role role = getOne(wrapper);
        SelectRoleByIdVO selectRoleByIdVO = BeanCopyUtils.beanCopyUtils(role, SelectRoleByIdVO.class);
        return ResponseResult.okResult(selectRoleByIdVO);
    }

    /**
     * @param updateRoleMenuDto
     * @return com.zhangzhan.domain.commcon.ResponseResult
     * @description 更新角色
     * @author 31115
     * @date 2022/12/7 22:41
     */
    @Override
    @Transactional
    public ResponseResult updateRole(UpdateRoleMenuDto updateRoleMenuDto) {

        //先删 角色对应的权限中间表id对应数据
        if (updateRoleMenuDto.getId() != null) {
            LambdaQueryWrapper<RoleMenu> wrapperr = new LambdaQueryWrapper<>();
            wrapperr.eq(RoleMenu::getRoleId,updateRoleMenuDto.getId());
            roleMenuService.remove(wrapperr);
        }


        try {
            //修改数据
            /*LambdaUpdateWrapper<Role> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Role::getId, updateRoleMenuDto.getId())
                    .set(Role::getRemark, updateRoleMenuDto.getRemark())
                    .set(updateRoleMenuDto.getRoleKey() != null, Role::getRoleKey, updateRoleMenuDto.getRoleKey())
                    .set(updateRoleMenuDto.getRoleName() != null, Role::getRoleName, updateRoleMenuDto.getRoleName())
                    .set(updateRoleMenuDto.getRoleSort() != null, Role::getRoleSort, updateRoleMenuDto.getRoleSort())
                    .set(Role::getStatus, updateRoleMenuDto.getStatus());
            Role role = getOne(wrapper);
            update(role,wrapper);*/

            Role role = BeanCopyUtils.beanCopyUtils(updateRoleMenuDto, Role.class);
            if (!StringUtils.hasText(role.getRoleName())){
                return ResponseResult.errorResult(500,"角色名称不能为空");
            }
            if ("".equals(role.getRoleSort().toString())){
                return ResponseResult.errorResult(500,"角色顺序不能为空");
            }
            if (!StringUtils.hasText(role.getRoleKey())){
                return ResponseResult.errorResult(500,"角色权限字符不能为空");
            }
            updateById(role);

            //插入中间表数据

                List<RoleMenu> roleMenuIdList = updateRoleMenuDto.getMenuIds()
                        .stream()
                        .map(new Function<Long, RoleMenu>() {
                            @Override
                            public RoleMenu apply(Long menuId) {
                                RoleMenu roleMenu = new RoleMenu();
                                roleMenu.setMenuId(menuId);
                                roleMenu.setRoleId(updateRoleMenuDto.getId());
                                return roleMenu;
                            }
                        }).collect(Collectors.toList());
                roleMenuService.saveBatch(roleMenuIdList);
                log.info("角色信息修改成功");
        } catch (Exception e) {
            log.error("角色数据修改失败 {}",e);
        }

        //返回状态
        return ResponseResult.okResult();
    }

    /**
     * @description 批量删除
     * @param ids
     * @return com.zhangzhan.domain.commcon.ResponseResult
     * @author 31115
     * @date 2022/12/8 0:11
     */
    @Override
    public ResponseResult deleteRoleById(Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        Role role = new Role();
        for (Long roleId : idList) {
            LambdaUpdateWrapper<Role> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Role::getId,roleId)
                    .set(Role::getDelFlag,"1");
            update(role,wrapper);
        }

        return ResponseResult.okResult();
    }

    /**
     * @description 查询的是所有状态正常的角色
     * 
     * @return com.zhangzhan.domain.commcon.ResponseResult<com.zhangzhan.domain.vo.SelectUserVO>
     * @author 31115 
     * @date 2022/12/8 9:34
     */
    @Override
    public ResponseResult<SelectUserVO> listAllRole() {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getDelFlag,"0")
                .eq(Role::getStatus,"0");
        List<Role> list = list(wrapper);
        List<SelectUserVO> vos = BeanCopyUtils.beanCopyUtil(list, SelectUserVO.class);
        return ResponseResult.okResult(vos);
    }


}

